import 'package:hive/hive.dart';
import '../models/expense_model.dart';

/// 记账服务类
/// 负责管理记账数据的本地存储和操作
class ExpenseService {
  static const String _boxName = 'expenses';
  static Box<ExpenseModel>? _box;

  /// 初始化服务
  static Future<void> init() async {
    if (_box == null || !_box!.isOpen) {
      _box = await Hive.openBox<ExpenseModel>(_boxName);
    }
  }

  /// 获取Box实例
  static Box<ExpenseModel> get box {
    if (_box == null || !_box!.isOpen) {
      throw Exception('ExpenseService not initialized. Call init() first.');
    }
    return _box!;
  }

  /// 添加记账条目
  static Future<void> addExpense(ExpenseModel expense) async {
    await box.put(expense.id, expense);
  }

  /// 更新记账条目
  static Future<void> updateExpense(ExpenseModel expense) async {
    await box.put(expense.id, expense);
  }

  /// 删除记账条目
  static Future<void> deleteExpense(String id) async {
    await box.delete(id);
  }

  /// 获取所有记账条目
  static List<ExpenseModel> getAllExpenses() {
    return box.values.toList()
      ..sort((a, b) => b.date.compareTo(a.date)); // 按日期倒序排列
  }

  /// 根据ID获取记账条目
  static ExpenseModel? getExpenseById(String id) {
    return box.get(id);
  }

  /// 获取指定日期范围的记账条目
  static List<ExpenseModel> getExpensesByDateRange(
    DateTime start,
    DateTime end,
  ) {
    return box.values.where((expense) {
      return expense.date.isAfter(start.subtract(const Duration(days: 1))) &&
          expense.date.isBefore(end.add(const Duration(days: 1)));
    }).toList()..sort((a, b) => b.date.compareTo(a.date));
  }

  /// 获取指定类型的记账条目
  static List<ExpenseModel> getExpensesByType(ExpenseType type) {
    return box.values.where((expense) => expense.type == type).toList()
      ..sort((a, b) => b.date.compareTo(a.date));
  }

  /// 获取指定分类的记账条目
  static List<ExpenseModel> getExpensesByCategory(ExpenseCategory category) {
    return box.values.where((expense) => expense.category == category).toList()
      ..sort((a, b) => b.date.compareTo(a.date));
  }

  /// 获取当月记账条目
  static List<ExpenseModel> getCurrentMonthExpenses() {
    final now = DateTime.now();
    final startOfMonth = DateTime(now.year, now.month, 1);
    final endOfMonth = DateTime(now.year, now.month + 1, 0);
    return getExpensesByDateRange(startOfMonth, endOfMonth);
  }

  /// 获取当年记账条目
  static List<ExpenseModel> getCurrentYearExpenses() {
    final now = DateTime.now();
    final startOfYear = DateTime(now.year, 1, 1);
    final endOfYear = DateTime(now.year, 12, 31);
    return getExpensesByDateRange(startOfYear, endOfYear);
  }

  /// 计算总收入
  static double getTotalIncome({DateTime? start, DateTime? end}) {
    List<ExpenseModel> expenses;
    if (start != null && end != null) {
      expenses = getExpensesByDateRange(start, end);
    } else {
      expenses = getAllExpenses();
    }

    return expenses
        .where((expense) => expense.type == ExpenseType.income)
        .fold(0.0, (sum, expense) => sum + expense.amount);
  }

  /// 计算总支出
  static double getTotalExpense({DateTime? start, DateTime? end}) {
    List<ExpenseModel> expenses;
    if (start != null && end != null) {
      expenses = getExpensesByDateRange(start, end);
    } else {
      expenses = getAllExpenses();
    }

    return expenses
        .where((expense) => expense.type == ExpenseType.expense)
        .fold(0.0, (sum, expense) => sum + expense.amount);
  }

  /// 计算净收入（收入 - 支出）
  static double getNetIncome({DateTime? start, DateTime? end}) {
    return getTotalIncome(start: start, end: end) -
        getTotalExpense(start: start, end: end);
  }

  /// 获取分类统计数据
  static Map<ExpenseCategory, double> getCategoryStatistics({
    ExpenseType? type,
    DateTime? start,
    DateTime? end,
  }) {
    List<ExpenseModel> expenses;
    if (start != null && end != null) {
      expenses = getExpensesByDateRange(start, end);
    } else {
      expenses = getAllExpenses();
    }

    if (type != null) {
      expenses = expenses.where((expense) => expense.type == type).toList();
    }

    final Map<ExpenseCategory, double> statistics = {};
    for (final expense in expenses) {
      statistics[expense.category] =
          (statistics[expense.category] ?? 0.0) + expense.amount;
    }

    return statistics;
  }

  /// 获取月度统计数据
  static Map<int, Map<String, double>> getMonthlyStatistics(int year) {
    final Map<int, Map<String, double>> monthlyStats = {};

    for (int month = 1; month <= 12; month++) {
      final startOfMonth = DateTime(year, month, 1);
      final endOfMonth = DateTime(year, month + 1, 0);
      final monthExpenses = getExpensesByDateRange(startOfMonth, endOfMonth);

      double income = 0.0;
      double expense = 0.0;

      for (final item in monthExpenses) {
        if (item.type == ExpenseType.income) {
          income += item.amount;
        } else {
          expense += item.amount;
        }
      }

      monthlyStats[month] = {
        'income': income,
        'expense': expense,
        'net': income - expense,
      };
    }

    return monthlyStats;
  }

  /// 清空所有数据
  static Future<void> clearAllData() async {
    await box.clear();
  }

  /// 关闭服务
  static Future<void> close() async {
    await _box?.close();
    _box = null;
  }
}
